package com.zyx.mpdemo.model.vo;

import com.zyx.mpdemo.helpers.utils.CourseStatisticsUtils;
import com.zyx.mpdemo.model.entity.Course;
import com.zyx.mpdemo.model.enums.CourseStatusEnums;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程详情
 *
 * @author Yaxi.Zhang
 * @since 2023/1/26 10:02
 */
@Data
@Accessors(chain = true)
public class CourseDetailVO {

    private String courseName;
    private String chapter;
    private CourseCost allCost;
    private CourseCost learnedCost;
    private CourseCost learningCost;
    private String learnedPercentage;

    public static CourseDetailVO getCourseDetail(String courseName, String chapter, List<Course> courses) {
        List<Course> learned = courses.stream()
            .filter(it -> Objects.equals(it.getCourseStatus(), CourseStatusEnums.LEARNED)).collect(Collectors.toList());
        List<Course> learning = courses.stream()
            .filter(it -> Objects.equals(it.getCourseStatus(), CourseStatusEnums.LEARNING)).collect(Collectors.toList());
        CourseCost allCost =  CourseStatisticsUtils.getCourseCost(courses);
        CourseCost learnedCost =  CourseStatisticsUtils.getCourseCost(learned);
        CourseCost learningCost =  CourseStatisticsUtils.getCourseCost(learning);
        double learnedPercentageDouble = CourseStatisticsUtils.getLearnedPercentage(learnedCost, allCost);
        String learnedPercentage = String.format("%.2f%%", learnedPercentageDouble * 100);
        return new CourseDetailVO()
            .setCourseName(courseName)
            .setChapter(chapter)
            .setAllCost(allCost)
            .setLearnedCost(learnedCost)
            .setLearningCost(learningCost)
            .setLearnedPercentage(learnedPercentage);
    }

    public static List<CourseDetailVO> getCourseDetails(String courseName, List<Course> allCourses) {
        List<CourseDetailVO> courseDetails = new ArrayList<>();
        Map<String, List<Course>> courseMap = new HashMap<>();
        List<String> chapters = new ArrayList<>();
        allCourses.forEach(course->{
            String chapter = course.getChapter();
            if (!chapters.contains(chapter)) {
                chapters.add(course.getChapter());
                List<Course> courseList = new ArrayList<>();
                courseList.add(course);
                courseMap.put(chapter, courseList);
            } else {
                courseMap.get(chapter).add(course);
            }
        });
        for (String chapter : chapters) {
            List<Course> courses = courseMap.get(chapter);
            courseDetails.add(getCourseDetail(courseName, chapter, courses));
        }
        return courseDetails;
    }

}
